﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using VinhSon.Intranet.Bussiness;
using VinhSon.Intranet.Models;

#endregion

namespace VinhSon.Intranet.Controllers
{
    public class UserController : BaseController
    {
        //
        // GET: /User/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetList(int start,
                                    int limit,
                                    string sort)
        {
            var query = UnitOfWork.UserRepository.Select(c => c.Inactive == false)
                                  .Select(c => new
                                                   {
                                                       c.Id,
                                                       c.Username,
                                                       c.Name,
                                                       c.IsActivated,
                                                       c.IsLockedOut,
                                                       c.LastLoginDate,
                                                       c.CreatedDate,
                                                       c.Remark
                                                   });
            return Content(FormatResult(query,
                                        c => c.OrderBy(v => v.Username),
                                        start,
                                        limit,
                                        sort,
                                        UserModel.Sort,
                                        c => c.Select(v => new
                                                               {
                                                                   v.Id,
                                                                   v.Username,
                                                                   v.Name,
                                                                   CreatedDate = v.CreatedDate == null
                                                                                           ? null
                                                                                           : new DateTime?(v.CreatedDate.Value.ToUniversalTime()),
                                                                   LastLoginDate = v.LastLoginDate == null
                                                                                           ? null
                                                                                           : new DateTime?(v.LastLoginDate.Value.ToUniversalTime()),
                                                                   v.Remark,
                                                                   v.IsActivated,
                                                                   v.IsLockedOut
                                                               })),
                           "json");
        }

        public ActionResult Add()
        {
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Add(UserModel userModel)
        {
            if (string.IsNullOrEmpty(userModel.Password))
                ModelState.AddModelError("Password", "This field is required");
            if (string.IsNullOrEmpty(userModel.ConfirmPassword))
                ModelState.AddModelError("ConfirmPassword", "This field is required");
            if (!string.IsNullOrEmpty(userModel.Password) && !string.IsNullOrEmpty(userModel.ConfirmPassword))
            {
                if (userModel.Password.Length < 6)
                    ModelState.AddModelError("Password", "Password field should be 6 characters");
                if (userModel.ConfirmPassword.Length < 6)
                    ModelState.AddModelError("ConfirmPassword", "Confirm Password field should be 6 characters");
                if (!userModel.Password.Equals(userModel.ConfirmPassword,
                                              StringComparison.CurrentCultureIgnoreCase))
                {
                    ModelState.AddModelError("Password", "Password not match");
                    ModelState.AddModelError("ConfirmPassword", "Password not match");
                }
            }
            if (ModelState.IsValid)
            {
                UpdateResult result = new UpdateResult();
                User user = userModel;
                if (UnitOfWork.UserRepository.CheckInsertUser(user))
                {
                    user.CreatedDate = DateTime.Now;
                    user.PasswordSalt = Constant.CreateSalt();
                    user.Password = Constant.CreatePasswordHash(userModel.Password,
                                                                user.PasswordSalt);
                    UnitOfWork.UserRepository.Insert(user);
                    UnitOfWork.Save();
                }
                else
                {
                    result.State = 4;
                    result.KeyLanguage = "user.add.username.exists";
                }
                return Json(Server.FormatResultToJson(result));
            }
            return Json(Server.FormatResultToJson(ModelState));
        }

        public ActionResult Edit(string id)
        {
            int guid;
            if (int.TryParse(id,
                            out guid))
            {
                User user = UnitOfWork.UserRepository.SelectbyId(guid);
                if (user != null)
                {
                    UserModel userModel = user;
                    return View(userModel);
                }
            }
            return RedirectToAction("Index");
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(UserModel userModel)
        {
            if (!string.IsNullOrEmpty(userModel.Password) && !string.IsNullOrEmpty(userModel.ConfirmPassword))
            {
                if (userModel.Password.Length < 6)
                    ModelState.AddModelError("Password", "Password field should be 6 characters");
                if (userModel.ConfirmPassword.Length < 6)
                    ModelState.AddModelError("ConfirmPassword", "Confirm Password field should be 6 characters");
                if (!userModel.Password.Equals(userModel.ConfirmPassword,
                                              StringComparison.CurrentCultureIgnoreCase))
                {
                    ModelState.AddModelError("Password", "Password not match");
                    ModelState.AddModelError("ConfirmPassword", "Password not match");
                }
            }
            if (ModelState.IsValid)
            {
                UpdateResult result = new UpdateResult();
                User user = UnitOfWork.UserRepository.SelectbyId(userModel.Id);
                userModel.Update(user);
                if (UnitOfWork.UserRepository.CheckUpdateUser(user))
                {
                    if (!string.IsNullOrEmpty(userModel.Password))
                    {
                        user.PasswordSalt = Constant.CreateSalt();
                        user.Password = Constant.CreatePasswordHash(userModel.Password,
                                                                    user.PasswordSalt);
                    }
                    UnitOfWork.UserRepository.Update(user);
                    UnitOfWork.Save();
                    return Json(Server.FormatResultToJson(result));
                }
            }
            return Json(Server.FormatResultToJson(ModelState));
        }

        [HttpPost]
        public ActionResult Delete(string id)
        {
            UpdateResult result = new UpdateResult();
            if (id != null)
            {
                string[] s = id.Split(',');
                int guid;
                List<int> list = (from s1 in s
                                  where int.TryParse(s1,
                                                     out guid)
                                  select int.Parse(s1)).ToList();

                if (UnitOfWork.UserRepository.CheckDeleteUser(list))
                {
                    UnitOfWork.UserRepository.Delete(list);
                    UnitOfWork.Save();
                }
                else
                {
                    result.State = 4;
                    result.KeyLanguage = UpdateResult.INFORMATION_IN_USED;
                }
            }
            else
            {
                result.State = 4;
                result.KeyLanguage = UpdateResult.INFORMATION_IN_USED;
            }
            return Json(Server.FormatResultToJson(result));
        }
    }
}
